#include "CJpegLoader.h"

#include <jpeg/jpeglib.h>
/*
//----------------------------------------------
struct CJpegErrorManager {
	struct jpeg_error_mgr pub;		// "public" fields

	jmp_buf setjmp_buffer;			// for return to caller

};

//----------------------------------------------
METHODDEF(void) my_error_exit (j_common_ptr cinfo)
{
	// cinfo->err really points to a my_error_mgr struct, so coerce pointer

	CJpegErrorManager* myerr = static_cast<CJpegErrorManager*>(cinfo->err);

	// Return control to the setjmp point

	longjmp(myerr->setjmp_buffer, 1);
}*/

//----------------------------------------------
bool CJpegLoader::load(CImage& oImage, const xstring& sPath)
{
	jpeg_decompress_struct	oDesc;

	FILE* pFile = NULL;
#ifdef USE_UNICODE
	errno_t oErr = _wfopen_s(&pFile, sPath.c_str(), CSTR("rb"));
#else
	errno_t oErr = fopen_s(&pFile, sPath.c_str(), CSTR("rb"));
#endif
	if (oErr || pFile == NULL)
		return false;

	jpeg_create_decompress(&oDesc);

	jpeg_stdio_src(&oDesc, pFile);

// 	jpeg_error_mgr			oJpegError;
// 	...
// 	oJpegError.err = jpeg_std_error();

	if (jpeg_read_header(&oDesc, TRUE) != JPEG_HEADER_OK)
	{
		fclose(pFile);
		return false;
	}

	jpeg_start_decompress(&oDesc);

	//int i = 0;
	//int iRowStride = oDesc.output_width * oDesc.output_components;
	oImage.m_pBuffer = new unsigned char[oDesc.output_width * oDesc.output_height * 3];
	oImage.m_iWidth = oDesc.output_width;
	oImage.m_iHeight = oDesc.output_height;

	for (unsigned int i=0; i<oDesc.output_height; i++)
	{
		unsigned char* pLine = &oImage.m_pBuffer[i];
		jpeg_read_scanlines(&oDesc, static_cast<JSAMPARRAY>( &pLine ), 1);
	}

	jpeg_finish_decompress(&oDesc);

	jpeg_destroy_decompress(&oDesc);

	fclose(pFile);

	return true;
}
